package com.example.gestureactivity;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class AnotherActivity extends BaseActivity implements OnTouchListener {

	private static final String TAG = "AnotherActivity";
	private ListView mLvAnother;
	private List<TextView> list;
	private RelativeLayout mLayout;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_another);
		initView();
	}

	private void initView() {
		mLayout = (RelativeLayout) findViewById(R.id.layout_another);
		mLvAnother = (ListView) findViewById(R.id.lv_another);
		list = new ArrayList<TextView>();
		for (int i = 0; i < 20; i++) {
			TextView textView = new TextView(this);
			textView.setText("This is item " + (i + 1));
			textView.setTextSize(25);
			list.add(textView);
		}

		MyAdapter adapter = new MyAdapter();
		mLvAnother.setAdapter(adapter);

		setListener();
	}

	@Override
	void onFlingFinished() {
		this.finish();
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return list.get(position);
		}

	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int action = event.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			startX = event.getX();
			startY = event.getY();
			break;
		case MotionEvent.ACTION_MOVE:
			Log.i(TAG, "touch: x = " + event.getX() + ", y = " + event.getY());
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			float currentX = event.getX();
			float currentY = event.getY();
			float dx = currentX - startX;
			float dy = currentY - startY;
			Log.e(TAG, "dx = " + dx + "," + "|dx| = " + Math.abs(dx)
					+ ",|dy| = " + Math.abs(dy));
			if (dx > 0 && Math.abs(dx) > Math.abs(dy)) {
				// 右划，而且水平方向的位移大于竖直方向的位移
				onFlingFinished();
			}
			break;

		}
		return false;
	}

	private void setListener() {
		for (int i = 0; i < mLayout.getChildCount(); i++) {
			mLayout.getChildAt(i).setOnTouchListener(this);
		}
	}

}
